package srx.open.com.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.greenrobot.event.EventBus;
import srx.open.com.R;
import srx.open.com.bean.CoursePublish;
import srx.open.com.bean.CourseSubscribe;
import srx.open.com.bean.User;
import srx.open.com.utils.Log;
import srx.open.com.utils.OpenToast;
import srx.open.com.utils.UserUtils;

public class LoginActivity extends ExtendBaseActivity {

    @Bind(R.id.left_lay)
    LinearLayout left_lay; // 返回.
    @Bind(R.id.left_tv)
    TextView left_tv; // 左边的标题文本.
    @Bind(R.id.right_lay)
    LinearLayout right_lay; // 找回密码

    @Bind(R.id.user_et)
    EditText user_et;
    @Bind(R.id.pass_et)
    EditText pass_et;
    @Bind(R.id.login_btn)
    Button login_btn; // 登录.

    @Bind(R.id.register_btn)
    TextView register_btn; // 立即注册.
    @Bind(R.id.shortcut_register_btn)
    TextView shortcut_register_btn; // 快捷注册.

    @Override
    public void initAllViews() {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        left_tv.setText("登录");
        initAllEventBus();
    }

    private void initAllEventBus() {
        EventBus.getDefault().register(this);
    }

    /**
     * 如果注册成功，发送信号，则将账号和密码填写进入.
     */
    public void onEvent(User user) {
        user_et.setText(user.getUsername());
//        pass_et.setText(user.getp());
    }

    /*
     * 登录.
     */
    @OnClick(R.id.login_btn)
    void onLoginBtn(View view) {
        String userName = user_et.getText().toString(); // 账号
        String pass = pass_et.getText().toString(); // 密码
        if (TextUtils.isEmpty(userName)) {
            OpenToast.showMsg("请输入账号");
            return;
        }
        if (TextUtils.isEmpty(pass)) {
            OpenToast.showMsg("请输入密码");
            return;
        }
        login(userName, pass); // 登录接口请求.
    }

    @Override
    public void onLoginSuccess() {
        OpenToast.showMsg("登陆成功");
        User user = UserUtils.getCurrentUser(mContext);
//		updateLocation(user); // 更新地理位置测试.
//		queryPubCourse(user); // 查询某用户的课程测试.
        EventBus.getDefault().post(user); // 更新我的页面信息.
        finish();
    }

    @Override
    public void onLoginFailure(int code, String msg) {
        OpenToast.showMsg(msg);
    }

    /*
     * 注册.
     */
    @OnClick(R.id.register_btn)
    void onRegisterBtnClick(View view) {
        Intent intents = new Intent(mContext, RegisterActivity.class);
        startActivity(intents);
    }

    /*
     * 快捷注册(无账号).
     */
    @OnClick(R.id.shortcut_register_btn)
    void onShortcutRegisterBtnClick(View view) {
        Intent intents = new Intent(mContext,
                NoAccountShortcutLoginActivity.class);
        startActivity(intents);
    }

    /*
     * 返回.
     */
    @OnClick(R.id.left_lay)
    void onLeftLayClick(View view) {
        finish();
    }

    /*
     * 忘记密码.
     */
    @OnClick(R.id.right_lay)
    void onRightLayClick(View view) {
        Intent intents = new Intent(mContext, ForgotPassActivity.class);
        startActivity(intents);
    }

    // ///////////////////////////////////////////////////////////////////////////////////////////
    // //////////// 服务器接口测试.
    // //////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 更新地理位置.
     */
    public void updateLocation(User user) {
        BmobGeoPoint point = new BmobGeoPoint(116.39727786183357, 30.789425); // 假设获取位置
        user.setLocation(point);
        user.update(mContext, new UpdateListener() {
            @Override
            public void onSuccess() {
                Log.d("更新地址位置成功!!!");
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("更新地址位置失败!!!");
            }
        });
    }

    CoursePublish mCoursePublish;

    int idCount = 0;

    /*
     * 发布课程
     */
    public void pubCourse(final User user) {
        mCoursePublish = new CoursePublish();
        // BmobACL bmobACL =new BmobACL(); // 权限测试.
        // bmobACL.setPublicReadAccess(true);
        // bmobACL.setPublicWriteAccess(true);
        // mCoursePublish.setACL(bmobACL);
        mCoursePublish.setUsertt(user);
        mCoursePublish.setContent("物理课程，想来的都可以，免费哦!!");
        mCoursePublish.save(mContext, new SaveListener() {

            @Override
            public void onSuccess() {
                Log.d("发布成功");
                courseAddToUser(user);
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("发布课程失败:" + code + " " + msg);
            }

        });
    }

    /**
     * 将 发布的课程 添加到用户的 发布课程信息 中.
     */
    public void courseAddToUser(final User user) {
        BmobRelation coursePublishs = new BmobRelation();
        coursePublishs.add(mCoursePublish);
        user.setPublishss(coursePublishs);
        user.update(mContext, new UpdateListener() {

            @Override
            public void onSuccess() {
                Log.d("已经添加成功");
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("添加失败" + code + " " + msg);
            }
        });
    }

    /**
     * 查询某用户发布的课程.
     */
    public void queryPubCourse(final User queryUser) {
        BmobQuery<CoursePublish> publishss = new BmobQuery<CoursePublish>();
        publishss.addWhereEqualTo("twoId", 11); // 添加分类搜索. 附近 + 分类 ，或者 地区 +
        /**
         * 注意这里的查询条件 第一个参数：是User表中的publishss字段名
         * 第二个参数：是指向User表中的某个用户的BmobPointer对象
         */
        publishss.addWhereRelatedTo("publishss", new BmobPointer(queryUser));
        publishss.findObjects(mContext, new FindListener<CoursePublish>() {

            @Override
            public void onSuccess(List<CoursePublish> coursePublishList) {
                Log.d("获取" + queryUser.getUsername() + "课程成功:"
                        + coursePublishList.size());
                // 测试浏览人数更新.
                for (CoursePublish coursePublish : coursePublishList) {
                    coursePublish.increment("browseCount");
                    coursePublish.update(mContext, new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(queryUser.getUsername() + "更新浏览人数成功");
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            Log.d(queryUser.getUsername() + "更新浏览人数失败!!!");
                        }
                    });
                }
            }

            @Override
            public void onError(int code, String msg) {
                Log.d("获取" + queryUser.getUsername() + "课程失败" + code + " "
                        + msg);
            }
        });
    }

    /**
     * 查找附近用户.
     */
    public void queryNearbyUsers() {
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        // 添加课程分类划分条件(课程为112的附近用户).
        BmobQuery<CoursePublish> innerQuery = new BmobQuery<CoursePublish>();
        innerQuery.addWhereEqualTo("twoId", 112);
        bmobQuery
                .addWhereMatchesQuery("publishss", "CoursePublish", innerQuery);
        //
        bmobQuery.addWhereNear("location", new BmobGeoPoint(116.39727786183,
                30.789425));
        bmobQuery.setLimit(10); // 获取最接近用户地点的10条数据 [分页].
        bmobQuery.findObjects(mContext, new FindListener<User>() {

            @Override
            public void onSuccess(List<User> userList) {
                OpenToast.showMsg("获取附近用户成功:" + userList.size());
                for (User user : userList) {
                    Log.d("user:" + user.toString());
                    queryPubCourse(user); // 查询某用户(附近)发布的课程.
                }
            }

            @Override
            public void onError(int code, String msg) {
                OpenToast.showMsg("获取附近用户失败" + code + " " + msg);
            }
        });
    }

    /**
     * 查找附近课程.
     */
    public void queryNearbyCourse() {
        BmobQuery<CoursePublish> bmobQuery = new BmobQuery<CoursePublish>();
        // bmobQuery.addWhereEqualTo("twoId", 11);
        // 添加课程分类划分条件(课程为11的附近用户).
        BmobQuery<User> innerQuery = new BmobQuery<User>();
        // innerQuery.addWhereNotEqualTo("username", ""); // 将自己排除出去.
        innerQuery.addWhereNear("location", new BmobGeoPoint(116.39727786183,
                30.789425));
        bmobQuery.addWhereMatchesQuery("usertt", "_User", innerQuery);
        //
        bmobQuery.setLimit(10); // 获取最接近用户地点的10条数据 [分页].
        bmobQuery.setSkip(0); // 分页效果
        bmobQuery.include("usertt"); // 获取这个发布课程的老师.
        bmobQuery.findObjects(mContext, new FindListener<CoursePublish>() {

            @Override
            public void onSuccess(List<CoursePublish> pubList) {
                OpenToast.showMsg("获取附近课程成功:" + pubList.size());
                for (CoursePublish pub : pubList) {
                    Log.d("pub:" + pub.getUsertt().getUsername() + " "
                            + pub.toString());
                }
            }

            @Override
            public void onError(int code, String msg) {
                OpenToast.showMsg("获取附近课程失败" + code + " " + msg);
            }
        });
    }

    /**
     * 统计数据.
     */
    public void getPubCount() {
        BmobQuery<CoursePublish> query = new BmobQuery<CoursePublish>();

        query.count(mContext, CoursePublish.class, new CountListener() {
            @Override
            public void onSuccess(int count) {
                Log.d("getCount:" + count);
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    // /////////////////////////////////////////////////////////

    /**
     * 用户订阅课程
     */
    public void subCourse(final User user) {
        final CourseSubscribe courseSubscribe = new CourseSubscribe();
        courseSubscribe.setState(0);
        courseSubscribe.setUsertt(user);
        courseSubscribe.save(mContext, new SaveListener() {
            @Override
            public void onSuccess() {
                subCourseAddToUser(user, courseSubscribe);
                Log.d("" + user.getUsername() + "订阅课程成功");
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("" + user.getUsername() + "订阅课程失败" + code + " " + msg);
            }
        });
    }

    /**
     * 订阅课程添加到用户关联上.
     */
    public void subCourseAddToUser(final User user,
                                   CourseSubscribe courseSubscribe) {
        BmobRelation courseSubscriber = new BmobRelation();
        courseSubscriber.add(courseSubscribe);
        user.setPublishss(courseSubscriber);
        user.update(mContext, new UpdateListener() {

            @Override
            public void onSuccess() {
                Log.d("已经添加成功");
                // 更新订阅人数.
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("添加失败" + code + " " + msg);
            }
        });
    }

    /**
     * 查询某用户订阅的课程.
     */
    public void querySubCourse(final User queryUser) {
        BmobQuery<CourseSubscribe> subscribess = new BmobQuery<CourseSubscribe>();
        subscribess
                .addWhereRelatedTo("subscribess", new BmobPointer(queryUser));
        subscribess.findObjects(mContext, new FindListener<CourseSubscribe>() {

            @Override
            public void onSuccess(List<CourseSubscribe> courseSubscribeList) {
                Log.d("获取" + queryUser.getUsername() + "订阅课程成功:"
                        + courseSubscribeList.size());
            }

            @Override
            public void onError(int code, String msg) {
                Log.d("获取" + queryUser.getUsername() + "订阅课程失败" + code + " "
                        + msg);
            }
        });
    }

}
